package com.rw.coco.handler.message.reply.handler.validate;

import com.rw.coco.api.data.CacheMapper;
import com.rw.coco.api.reply.mapper.AdvancedReply;
import com.rw.coco.handler.message.event.CocoPrivateMessageEvent;
import com.rw.coco.handler.message.reply.PrivateReplyHandler;
import com.rw.coco.handler.message.reply.util.FrequencyLimit;
import com.rw.tool.util.string.StringFormatter;

/**
 * 个人频率限制器
 */
public class PrivateFrequencyHandler extends PrivateReplyHandler {
    @Override
    protected boolean privateTrigger(CocoPrivateMessageEvent privateEvent) {
        // 获取频率token
        final String frequencyTokenTemplate = "com.rw.coco.frequency.group.{}";
        String senderId = privateEvent.getSender().getId();
        String frequencyToken = StringFormatter.format(frequencyTokenTemplate, senderId);

        // 判断频率是否超频
        CacheMapper cacheMapper = privateEvent.getCacheMapper();
        // 如果超频，则拦截
        FrequencyLimit frequencyLimit = privateEvent.getCocoData().getFrequencyLimit();
        return frequencyLimit.countPrivateFreq(frequencyToken);
    }

    @Override
    protected void privateHandler(CocoPrivateMessageEvent privateEvent) {
        // 获得回复对象
        FrequencyLimit frequencyLimit = privateEvent.getCocoData().getFrequencyLimit();
        AdvancedReply advancedReply = privateEvent.getReplyApi().getAdvancedReply();

        // 获取警告token
        final String warnTokenTemplate = "com.rw.coco.warn.group.{}";
        String senderId = privateEvent.getSender().getId();
        String warnToken = StringFormatter.format(warnTokenTemplate, senderId);

        // 判断警告是否超频
        CacheMapper cacheMapper = privateEvent.getCacheMapper();
        int warnExceeded = frequencyLimit.warn(warnToken);
        String nickname = privateEvent.getSender().getNick();
        // 如果未超频则正常警告
        if (warnExceeded < frequencyLimit.maxWarnCount) {
            // 回复警告对话
            String reply = advancedReply.privateFreqExceededWarn(privateEvent, warnExceeded, frequencyLimit.maxWarnCount);
            privateEvent.sendBack(reply);

            // 输出日志
            final String logTemplate = "好友/群友 {}({}) 对话超频，警告 {} 次";
            String log = StringFormatter.format(logTemplate, senderId, nickname, warnExceeded);
            privateEvent.getCocoLogger().info(log);
        } else {
            // 如果警告次数超过限制，回复退群信息
            String reply = advancedReply.privateFreqExceeded(privateEvent, frequencyLimit.maxWarnCount);
            privateEvent.sendBack(reply);

            // 退群，拉黑
            privateEvent.delete();
            privateEvent.getPersistenceMapper().getAccountMapper().blackOrWhiteAccount(senderId, true);

            // 输出日志
            final String logTemplate = "好友/群友 {}({}) 对话超频，警告无效，已删除好友，拉黑处理";
            String log = StringFormatter.format(logTemplate, senderId, nickname);
            privateEvent.getCocoLogger().info(log);

            // 清除缓存
            cacheMapper.delete(warnToken);
        }
    }
}
